import captcha as captcha
from django.forms import model_to_dict
from django.http import HttpResponse
import re
import json
from django.views.decorators.csrf import csrf_exempt
from django.middleware import csrf
from UserProfile import models
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse

# 验证码需要导入的模块
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
import base64
# Create your views here.

@csrf_exempt
def index(request):
    token = csrf.get_token(request)
    return HttpResponse(json.dumps({'token': token}))

@csrf_exempt
def register(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        # username = "sadasd"
        # return HttpResponse(username)
        email = request.GET.get('email' ,None)
        passwd = request.GET.get('passwd' ,None)
        repasswd = request.GET.get('repasswd' ,None)
        captchaStr = request.GET.get('captcha' ,None)
        captchaHashkey = request.GET.get('captchaHashkey' ,None)
        # print(type(captchaHashkey))
        if checkCaptcha(captchaStr,captchaHashkey)==False:
            code = 0
            msg = "验证码错误！"
            data = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(data))
        if len(username)<6:
            code = 0
            msg = "用户名长度不小于6！"
            data = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(data))
        matchUserName = re.match(r'^[A-Za-z0-9]+$', username)
        if  matchUserName ==None:
            code = 0
            msg = "用户名由字母和数字组成！"
            errorData = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(errorData))
        compileEmail = re.compile(r'^\w+@(\w+\.)+(com|cn|net)$')
        searchEmail = compileEmail.search(email)
        if searchEmail==None:
            code = 0
            msg  = "邮箱格式不正确！"
            errorData = {'code':code,'msg':msg}
            return HttpResponse(json.dumps(errorData))
        flag = 0
        try:
            models.User.objects.get(username=username)
            flag = 1
        except :
            pass
        if flag==1:
            code = 0
            msg  = "用户名已存在！"
            errorData = {'code':code,'msg':msg}
            return HttpResponse(json.dumps(errorData))
        try:
            models.User.objects.get(email=email)
            flag=1
        except :
            pass
        if flag==1:
            code = 0
            msg  = "邮箱已存在！"
            data = {'code':code,'msg':msg}
            return  HttpResponse(json.dumps(data))
        check = checkPass(passwd,repasswd)
        if check['code']==0:
            return HttpResponse(json.dumps(check))
        data= {'username': username, 'password': make_password(passwd, None, 'pbkdf2_sha256'),'email':email}
        res = models.User.objects.create(**data)
        print(res)
        code = 1
        msg = "注册成功！"
        successData = {'code':code,'msg':msg}
        return HttpResponse(json.dumps(successData))



def checkPass(passwd,repasswd):
    if len(passwd) <6:
        code = 0
        msg = "密码长度不小于6"
    elif passwd!=repasswd:
        code = 0
        msg = "密码不一致！"
    else:
        code = 1
        msg = "验证成功"
    data  = {'code':code,'msg':msg}
    return data



@csrf_exempt
def login(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        password = request.GET.get('passwd')
        captchaStr = request.GET.get('captcha' ,None)
        captchaHashkey = request.GET.get('captchaHashkey' ,None)
        # print(type(captchaHashkey))
        if checkCaptcha(captchaStr,captchaHashkey)==False:
            code = 0
            msg = "验证码错误！"
            data = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(data))
        try:
            res = models.User.objects.filter(username=username).values('password')
            flag = 1
        except :
            code = 0
            msg  = "用户名不存在！"
            errorData = {'code':code,'msg':msg}
            return HttpResponse(json.dumps(errorData))
        if check_password(password,res[0]['password']):
            code = 1
            msg  = "登录成功！"
            successData = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(successData))
        else:
            code = 0
            msg  = "用户名或密码错误！"
            errorData = {'code': code, 'msg': msg}
            return HttpResponse(json.dumps(errorData))







# 创建验证码
def captcha():
    # 验证码，第一次请求
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha


def refreshCaptcha(request):
    return HttpResponse(json.dumps(captcha()), content_type='application/json')


# 验证验证码
def checkCaptcha(captchaStr, captchaHashkey):
    if captchaStr and captchaHashkey:
        try:
            # 获取根据hashkey获取数据库中的response值
            get_captcha = CaptchaStore.objects.get(hashkey=captchaHashkey)
            # 如果验证码匹配
            if get_captcha.response == captchaStr.lower():
                return True
            else:
                return False
        except:
            return False
    else:
        return False
